/**
* @description: 现场实施-施工执行
* @author: zhaohui
* @data:2023年月14日
* @remark:
**/
<template>
	<view class="content">
		<nav-bar class="header" :background="backgroundColor" back :title="title" @goBack="goBack">
			<!-- <text class="save_btn" slot="scan" @click="goSave">保存</text> -->
		</nav-bar>

		<view class="container" v-if="surveyArr.length>0">
			<div id="directory" class="directory" ref="wrapper" v-if="recordData.length>0">
				<ul :class="isExpand?'expand-ul':''" ref="scroller">
					<li :class="[{'active': curSort==item.sort}, 'li-number']"
						:style="{'backgroundColor':libgColor[item.isExecute]}" @click="handleSelectLi(item)"
						v-for="(item, index) in recordData" :key="index">
						{{item.sort}}
					</li>
				</ul>
				<view class="expand-wrap">
					<van-icon :name="isExpand?'arrow-up':'arrow-down'" @click="toggleArrow" />
				</view>
			</div>
			<view class="title">
				<span class="t-number">{{curSort}}</span> {{curSurveyObj}}
			</view>
			<view class="card-wrap" v-for="(item, index) in surveyArr" :key="index">
				<view class="w-row-3">
					作业内容：{{item.workContent}}
				</view>
				<view class="w-row-4">
					<view class="r-4-label isrequired">现场照片:<span>（最多上传3张）</span></view>
					<view class="image-wrap">
						<view class="image-list">
							<view class="upload-button" v-for="(imgItem, idx) in item.filePath" :key="idx">
								<view v-if="imgItem.img" class="delete-icon"
									@click.stop="imageHandle(idx,imgItem, 'DELETE',index)">
									×</view>
								<img v-if="imgItem.img" :src="imgItem.img" alt=""
									@click.stop="imageHandle(idx,imgItem, 'PREVIEW', index)">
							</view>
							<img class="upload-button" v-if="item.filePath.length < wxCount"
								src="../../../../static/img/ywgj.png" alt=""
								@click.stop="imageHandle(0,null, 'CHOOSE', index)">
						</view>
					</view>
				</view>
				<view class="w-row-5">
					<view class="r-5-label isrequired">现场落地情况说明</view>
					<textarea class="r-5-remark" v-model="item.situationDescription" placeholder="情况说明" />
				</view>
			</view>
		</view>
		<view class="sub-btn-container">
			<van-button class="submit-btn" block type="info" :disabled="!submintStatus" color="#417ADC"
				@click="executeSubmit">保存{{curSort < recordData.length ? '，下一项' : ''}}
			</van-button>
		</view>
		<van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
			<van-swipe>
				<div v-for="(image, index) in fileList" :key="index">
					<van-swipe-item v-if="image.img" style="text-align: center;">
						<img :src="image.img" />
					</van-swipe-item>
				</div>
			</van-swipe>
		</van-popup>
	</view>
</template>
<script>
	import navBar from '../../../../components/common/nav-bar'
	import wx from '../../../../static/common_js/jweixin_1.0.0'
	import {
		Dialog,
		Toast
	} from 'vant'
	import axios from 'axios'
	import {
		mapGetters
	} from 'vuex'
	import baseConfig from "../../../../common/config";
	let config = {}
	baseConfig.getOptions.then(res => {
		config = res
	})
	export default {
		name: 'index',
		components: {
			navBar
		},
		props: {},
		data() {
			return {
				baseUrl: "",
				initDataParam: "",
				backgroundColor: '#417ADC',
				title: '施工执行',
				workId: '',
				curSort: 1, //执行任务列表默认
				curSurveyObj: '',
				allSurverData: [],
				recordData: [],
				surveyIndex: 0,
				surveyArr: [], //选中项目的数据
				isExpand: false,
				libgColor: {
					0: '#C9C9C9', // 未完成
					1: '#3CDA68' // 已完成
				},
				showPreview: false, //图片预览
				fileList: [],
				selectIndex: 0, //用于移动到下一项作业
				wxCount: 3, //相册可选取数量，默认3张
				base64List: [], //相册文件数据
			}
		},
		computed: {
			...mapGetters(['userData']),
			submintStatus: function() {
				if (this.surveyArr.length > 0) {
					let imgStatus = []
					let textStatus = []
					this.surveyArr.forEach(item => {
						textStatus.push(!item.situationDescription ? 0 : 1)
						if (item.file && item.file.length > 0) {
							imgStatus.push(!item.file[0].img ? 0 : 1)
						}
					})
					return !imgStatus.includes(0) && !textStatus.includes(0)
				}
			}
		},
		watch: {},
		mounted() {},
		onLoad(option) {
			this.initDataParam = JSON.parse(decodeURIComponent(option.message))
			this.getSurverData()
			this.baseUrl = config.firstUrl
			// this.baseUrl = `http://${this.$apiRequest.bzhzyApi.fileUrl}`
		},
		methods: {
			goBack() {
				uni.navigateBack()
			},
			/**
			 * 通知上一个页面刷新数据
			 */
			back() {
				let pages = getCurrentPages()
				let prevPage = pages[pages.length - 2] //上一个页面
				prevPage.isRefresh = true
				uni.navigateBack()
			},
			getSurverData() {
				this.$apiRequest.bzhzyApi
					.constructionviwe({
						workPlanId: this.initDataParam.id,
						consultationDeductionId: this.initDataParam.objId
					})
					.then(res => {
						this.allSurverData = res.data
						this.recordData = this.genRecord(res.data)
						this.handleSelectLi(this.recordData[this.selectIndex])
					})
			},
			genRecord(arr) {
				let newArr = []
				if (arr && arr.length > 0) {
					arr.forEach(item => {
						newArr.push({
							sort: item.sort,
							isExecute: item.isFinsh ? item.isFinsh : 0,
							objId: item.operatingItemId
						})
					})
				}
				return newArr
			},
			selectCurItem() {
				if (this.allSurverData && this.allSurverData.length > 0) {
					this.allSurverData.filter(item => {
						if (item.sort === this.curSort) {
							this.surveyArr = []
							this.curSurveyObj = item.hazardPointAnalysis
							item.filePath.map(itemFile => {
								itemFile['img'] = itemFile.img ? itemFile.img : (itemFile.url ? this
									.baseUrl + itemFile.url : "")
								itemFile['raw'] = itemFile.raw ? itemFile.raw : null
								return itemFile
							})
							this.surveyArr.push(item)
							
						}
						return item
					})
				}
			},
			handleSelectLi(e) {
				this.curSort = e.sort
				this.selectCurItem()
			},
			toggleArrow() {
				this.isExpand = !this.isExpand
			},
			goSave() {
				this.$apiRequest.bzhzyApi.insertMULTconstruction({
					workPlanId: this.initDataParam.id,
					consultationDeductionId: this.initDataParam.objId
				}).then(res => {
					Toast(res.msg)
					this.back()
				}).catch(error => {
					Toast(error)
				})
			},
			executeSubmit() {
				Toast.loading({
					duration: 0,
					message: '加载中...',
					forbidClick: true
				})
				var formData = new FormData()
				this.surveyArr.forEach((item, index) => {
					item.filePath.map(e => {
						if (e.raw) formData.append("files", e.raw)
					})

					formData.append("workPlanId", this.initDataParam.id) //计划id
					formData.append("consultationDeductionId", this.initDataParam.objId) //施工流程节点id
					formData.append("operatingItemId", item.operatingItemId) //施工项目id
					formData.append("situationDescription", item.situationDescription) // 情况说明
				})

				let config = {
					headers: {
						'Content-Type': 'multipart/form-data',
						Authorization: uni.getStorageSync('token') || ''
					}
				}
				let url = ''
				// #ifndef IGW
				url = '/bzzy/web/api/consultationdeduction/insertONEconstruction'
				// #endif
				// #ifdef IGW
				url = `${this.baseUrl}/bzzy/web/api/consultationdeduction/insertONEconstruction`
				// #endif
				
				// url =
				// 	`http://${this.$apiRequest.bzhzyApi.fileUrl}/bzzy/web/api/consultationdeduction/insertONEconstruction`
				
				axios.post(url, formData, config).then(res => {
					Toast.clear()
					Toast(res.data.msg)
					if (res.data.code == 0) {
						let index = this.recordData.findIndex(item => item.sort === this.curSort)
						//this.selectIndex是0开始 所以this.recordData.length长度要-1,防止刷新数据超出范围
						if (this.selectIndex < this.recordData.length - 1) {
							this.selectIndex = index + 1
						} else {
							this.selectIndex = index
						}
						if (res.data.data.isFinsh) {
							Dialog.confirm({
									message: '是否确认提交，提交后不能修改',
									confirmButtonColor: '#417adc'
								})
								.then(() => {
									this.goSave()
								})
								.catch(() => {

								})
						}
						this.getSurverData()
					} else if (res.data.code == 401) {
						Dialog.alert({
							message: "当前页面信息已失效",
							confirmButtonText: "重新加载",
							theme: "round-button",
						}).then(() => {
							uni.reLaunch({
								url: "/pages/SSOLogin"
							});
						})

					}
				})
			},
			imageHandle(imgIndex, imgItem, handleType, index) {
				this.surveyIndex = index
				if (handleType === 'CHOOSE') {
					// let base64List = []
					// let base64File =
					// 	""
					// let fileRaw = this.dataURLtoFile(base64File, "test.jpeg")
					// base64List.push({
					// 	raw: fileRaw,
					// 	img: base64File,
					// })
					// base64List.forEach(img => {
					// 	this.surveyArr[this.surveyIndex].filePath.push(img)
					// })
					this.choosePhoto()
				} else if (handleType === 'PREVIEW') {
					this.fileList = [imgItem]
					this.showPreview = true
				} else if (handleType === 'DELETE') {
					Dialog.confirm({
							message: '删除后不可恢复，是否确定删除？',
							confirmButtonColor: '#417adc'
						})
						.then(() => {
							this.deleteFileChange(imgIndex, imgItem, index)
						})
						.catch(() => {
							// on cancel
						})

				}
			},
			deleteFileChange(imgIndex, imgItem, index) {
				//本地上传-删除文件，raw=null 走删除文件接口
				if (imgItem.raw) {
					this.surveyArr[index].filePath.splice(imgIndex, 1)
				} else {
					this.deleteFile(imgItem)
				}
			},
			/**
			 * 删除文件接口，当每一项数据的三张图片删全部除，需要改为未提交状态（现阶段请求接口）
			 * @param {Object} fileData
			 */
			deleteFile(fileData) {
				this.$apiRequest.bzhzyApi.delFileInfo({
					fileId: fileData.fileId,
				}).then(res => {
					Toast(res.msg)
					let index = this.recordData.findIndex(item => item.sort === this.curSort)
					this.selectIndex = index
					this.getSurverData()
				})

			},
			choosePhoto() {
				let _this = this
				//相册可选的数量
				let num = 0
				this.surveyArr[this.surveyIndex].filePath.forEach(item => {
					if (item.img) {
						num++
					}
				})
				let selectNum = this.wxCount - num
				wx.chooseImage({
					count: selectNum,
					sourceType: ['album', 'camera'],
					success: chooseImageRes => {
						_this.syncLocalImg(chooseImageRes.localIds)
					},
					fail: error => {
						console.log(error)
					}
				})
			},
			async syncLocalImg(localIds) {
				this.base64List = []
				for (let i = 0; i < localIds.length; i++) {
					await this.syncUpload(localIds[i], i, localIds.length)
				}
			},
			syncUpload(localId, i, localIdsLength) {
				let self = this;
				return new Promise(resolve => {
					wx.getLocalImgData({
						localId, // 图片的localID
						success: function(resBackData) {
							let localData = resBackData.localData;
							let imageBase64 = ''
							const photoName = `${new Date().getTime()}`
							//判断是否有这样的头部
							if (localData.indexOf('data:image') == 0) {
								//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
								imageBase64 = localData
							} else {
								//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
								//此时一个正常的base64图片路径就完美生成赋值到img的src中了
								imageBase64 =
									'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
							}
							//直接使用imageBase64展示，会导致swipe卡顿
							let file = self.dataURLtoFile(imageBase64,
								`${photoName}.jpeg`)
							let blob = self.h5_url_to_blob(imageBase64)
							self.base64List.push({
								raw: file,
								img: URL.createObjectURL(blob),
							})
							if (i + 1 === localIdsLength) {
								self.base64List.forEach(img => {
									self.surveyArr[self.surveyIndex].filePath.push(img)
								})
							}
							resolve("ok")
						},
					})
				})
			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], filename, {
					type: mime
				})
			},
			h5_url_to_blob(url) {
				let arr = url.split(',')
				let mime = arr[0].match(/:(.*?);/)[1]
				let bstr = atob(arr[1])
				let n = bstr.length
				let u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new Blob([u8arr], {
					type: mime
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	.content {
		width: 100vw;
		height: 100vh;
		background: #f2f6fa;

		.save_btn {
			font-size: px2vw(54);
			margin-right: px2vw(40);
		}

		.container {
			height: calc(100vh - #{px2vh(163)});
			overflow: auto;
			background: #f2f6fa;

			.title {
				padding: px2vw(10) px2vw(30);
				margin: px2vw(20) auto;

				.t-number {
					display: inline-block;
					width: px2vw(80);
					height: px2vw(80);
					border-radius: 50%;
					background: #417adc;
					color: #fff;
					font-weight: bold;
					text-align: center;
					line-height: px2vw(80);
					margin-right: px2vw(20);
				}
			}

			.card-wrap {
				// height: 400px;
				margin: 0 px2vw(30) px2vw(180) px2vw(30);
				padding: px2vw(50);
				border-radius: px2vw(20);
				background: #fff;
			}

			.w-row-1 {
				display: flex;
				align-items: center;
				justify-content: space-between;
				background: #f7f7f7;
				min-height: px2vw(120);
				margin: px2vw(20) auto;
				border-radius: px2vw(20);

				.row-l {
					display: flex;
					align-items: center;
					flex: 1;

					img {
						width: px2vw(60);
						height: px2vw(60);
						margin: 0 px2vw(10);
					}

					span {
						margin: px2vw(10) 0;
						// width: 154px;
						color: #417adc;
					}
				}
			}

			.w-row-2 {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				opacity: 0.8;
				font-size: px2vw(40);
				font-weight: 700;
				text-align: left;
				color: #666666;

				.r-l,
				.r-r {
					flex: 1;
					font-size: px2vw(42);

					span {
						color: #417adc;
					}
				}
			}

			.w-row-3 {
				margin: px2vw(10) 0;
				padding: px2vw(40);
				background: #f7f7f7;
				border-radius: px2vw(15);
				opacity: 0.7;
				font-size: px2vw(42);
				font-weight: 400;
				text-align: left;
				color: #666666;
			}

			.w-row-4 {
				.r-4-label {
					font-size: px2vw(42);
					font-weight: 400;
					text-align: left;

					span {
						opacity: 0.7;
						color: #666666;
					}
				}
			}

			.w-row-5 {
				.r-5-label {
					font-size: px2vw(40);
					font-weight: 400;
					text-align: left;
				}

				.r-5-remark {
					min-height: px2vw(200);
					width: initial;
					padding: px2vw(40);
					background: #f7f7f7;
					border-radius: px2vw(20);
					margin: px2vw(20) 0 px2vw(40);
				}
			}

			.btn-container {
				margin: px2vw(80) px2vw(30);
				background: #f2f6fa;
				display: flex;
				justify-content: space-between;

				.van-button {
					height: px2vw(100);
					width: px2vw(450);
					border-radius: $border-radius-base;
				}
			}
		}

		.sub-btn-container {
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: px2vw(180);
			background: #f2f6fa;
			// padding-bottom: 100px;

			.submit-btn {
				margin: 0 px2vw(30);
				border-radius: px2vw(20);
			}
		}

		.image-wrap {
			display: flex;
			width: calc(100vw - #{px2vw(140)});
			height: px2vw(230);
			margin: px2vw(49) auto;
			padding-left: px2vw(40);

			.image-list {
				width: 100%;
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.upload-button {
					width: px2vw(230);
					height: px2vw(230);
					background-size: cover;
					position: relative;
					// background-image: url('../../../../static/img/ywgj.png');
					margin-right: px2vw(75);

					img {
						width: 100%;
						height: px2vw(230);
						border-radius: px2vw(6);
					}

					.delete-icon {
						position: absolute;
						top: px2vw(-20);
						right: px2vw(-20);
						width: px2vw(40);
						height: px2vw(40);
						background-color: #ff4355;
						border-radius: 50%;
						color: #fff;
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}
			}
		}

		.directory {
			width: 100vw;
			background: #fff;
			padding: px2vw(20);
			overflow: auto;

			&::-webkit-scrollbar {
				width: 0 !important;
				height: 0 !important;
				display: none;
			}

			ul {
				display: inline-flex;
				padding: px2vw(20);

				li.li-number {
					display: inline-block;
					width: px2vw(80);
					height: px2vw(80);
					border-radius: 50%;
					background: #417adc;
					color: #fff;
					font-weight: bold;
					text-align: center;
					line-height: px2vw(80);
					margin-right: px2vw(20);

					&.active {
						background: #417adc !important;
					}

					&:last-child {
						margin-right: px2vw(200);
					}
				}
			}

			.expand-wrap {
				position: fixed;
				z-index: 99;
				right: 0;
				top: px2vh(163);
				width: px2vw(68);
				height: px2vw(120);
				line-height: px2vw(150);
				text-align: right;
				background: linear-gradient(-90deg, #ffffff 40%, rgba(255, 255, 255, 0) 100%);
				font-size: px2vw(18);
				padding-right: px2vw(20);
			}
		}

		.isrequired::before {
			content: '*';
			color: #ff4355;
			display: inline-block;
		}

		// 头部目录列表
		.directory {
			position: sticky;
			top: px2vw(0);
			z-index: 99;
			background: #fff;
			padding: px2vw(10) 0;
			overflow: auto;

			&::-webkit-scrollbar {
				width: 0 !important;
				height: 0 !important;
				display: none;
			}

			ul {
				display: inline-flex;
				padding-left: px2vw(40);

				li.li-number {
					display: inline-block;
					width: px2vw(80);
					height: px2vw(80);
					border-radius: 50%;
					background: #c9c9c9;
					color: #fff;
					// font-weight: bold;
					text-align: center;
					line-height: px2vw(80);
					margin-right: px2vw(20);

					&:last-child {
						margin-right: px2vw(40);
					}
				}
			}
		}

		.expand-ul {
			display: flex;
			flex-wrap: wrap;
			padding-right: px2vw(80);

			li {
				margin-bottom: px2vw(16);
			}
		}

		.van-preview-wrap {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;

			.van-swipe {
				width: 100%;
				height: 100%;
			
				.van-swipe-item {
					display: flex;
			
					img {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
				}
			}
		}

		.van-popup {
			background-color: rgba(0, 0, 0, 0.8);

			.van-cell {
				position: absolute;
				bottom: 0;
				border-top: px2vw(10) solid #eee;
				z-index: 3;
			}
		}
	}
</style>
